package com.lihao.wanandroid.ui.main

import android.os.Bundle
import androidx.core.view.get
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.lihao.jetpackcore.base.BaseViewModel
import com.lihao.jetpackcore.ext.getActivityViewModel
import com.lihao.wanandroid.R
import com.lihao.wanandroid.app.base.BaseFragment
import com.lihao.wanandroid.app.ext.init
import com.lihao.wanandroid.ui.mine.*
import com.lihao.wanandroid.ui.home.HomeFragment
import com.lihao.wanandroid.ui.navigation.NavigationFragment
import com.lihao.wanandroid.ui.project.ProjectClassifyFragment
import com.lihao.wanandroid.ui.tree.TreeFragment
import kotlinx.android.synthetic.main.fragment_main.*
import timber.log.Timber

/**
 * Created by lihao on 2020/5/18.
 * Describe: 主页Fragment
 */
class MainFragment : BaseFragment<BaseViewModel>() {

    var fragments = arrayListOf<Fragment>()
    private val homeFragment: HomeFragment by lazy { HomeFragment() }
    private val navigationFragment: NavigationFragment by lazy { NavigationFragment() }
    private val treeFragment: TreeFragment by lazy { TreeFragment() }
    private val projectFragment: ProjectClassifyFragment by lazy { ProjectClassifyFragment() }
    private val mineFragment: MineFragment by lazy { MineFragment() }

    private val mainViewModel: MainViewModel by lazy { getActivityViewModel<MainViewModel>() }

    init {
        fragments.apply {
            add(homeFragment)
            add(navigationFragment)
            add(treeFragment)
            add(projectFragment)
            add(mineFragment)
        }
    }

    override fun layoutId() = R.layout.fragment_main

    override fun initView(savedInstanceState: Bundle?) {
        // 初始化viewpager2
        viewPager.init(this, fragments, false).run {
            offscreenPageLimit = fragments.size
        }
        navigationView.run {
            setOnNavigationItemSelectedListener {
                when (it.itemId) {
                    R.id.item_host -> viewPager.setCurrentItem(0, false)
                    R.id.item_navigation -> viewPager.setCurrentItem(1, false)
                    R.id.item_tree -> viewPager.setCurrentItem(2, false)
                    R.id.item_project -> viewPager.setCurrentItem(3, false)
                    R.id.item_mine -> viewPager.setCurrentItem(4, false)
                }
                true
            }
        }
    }

    override fun lazyLoadData() {
    }

    override fun createObserver() {
        mainViewModel.curPageLiveData.observe(this, Observer {
            if (it > fragments.size - 1) {
                Timber.d("超出Fragment数量")
                return@Observer
            }
            viewPager.setCurrentItem(it, false)
            navigationView.menu[it].isChecked = true
        })
    }
}